<?php

namespace app\libs\exception;

use Webman\Exception\ExceptionHandler as Handle;
use Webman\Http\Request;
use Webman\Http\Response;

use support\exception\BusinessException;
use Throwable;

class ExceptionHandler extends Handle
{
    private $code;
    private $status;
    private $msg;

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    public function render(Request $request, Throwable $e): Response
    {
        if (($e instanceof BusinessException) && ($response = $e->render($request))) {
            return $response;
        }

        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->status = $e->status;
            $this->msg = $e->msg;
        } else {
            if (!getenv('APP_DEBUG')) {
                $this->code = 500;
                $this->status = 0;
                //$this->msg = '您访问的页面不存在！';
                $this->msg = $e->getMessage();
            } else {
                // 其他错误交给系统处理
                return parent::render($request, $e);
            }
        }

        $result = [
            'code' => $this->code,
            'status' => $this->status,
            'msg' => $this->msg,
            //'request_url' => $request->url()
            'data' => ['request_url' => $request->url()]
        ];

        return json($result, $this->code);
    }
}